package gui;

import iCalImport.SaveDialog;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import tools.CheckboxUser;
import tools.OptionReader;

/**
 * Klasse erzeugt Fenster um Kalender zu erstellen
 * 
 * @author Michi
 * 
 */
public class NewCalendarWindow extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1872348462455994967L;
	private OptionReader or;
	private String[] windowColorsSeperated;
	private int r;
	private int g;
	private int b;
	private DefaultListModel dlm;
	private CheckBoxList users;
	private Connection connection;
	private Statement stat;
	private LinkedList<CheckboxUser> llUser = new LinkedList<CheckboxUser>();

	// Sprache
	int speak = 1;
	String[] fenstername = { "Kalender Hinzuf\u00FCgen", "Add Calendar",
			"Calendarium Addere" };
	String[] buttonadd = { "Hinzufügen", "Add", "Addicere" };
	String[] buttoncancel = { "Abbrechen", "Cancel", "Destruere" };
	String[] textname = { "Name:", "Name:", "Nomen:" };
	String[] einladen = { "Zu Kalender einladen:", "Invite to calendar:",
			"Duis Calendar:" };
	private JTextField textField;

	/**
	 * Kosntruktor
	 * 
	 * @param openedfrom
	 *            Instanz welche diese Klasse aufruft
	 */
	public NewCalendarWindow(final Object openedfrom) {

		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);
		speak = Integer.parseInt(or.getLanguage());

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setTitle(fenstername[speak]);

		Dimension size = new Dimension(300, 350);
		setSize(size);
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);

		setBackground(new Color(r, g, b));
		getContentPane().setLayout(null);

		JLabel name = new JLabel();
		name.setBounds(20, 24, 256, 28);
		name.setText(textname[speak]);
		getContentPane().add(name);

		textField = new JTextField();
		textField.setBounds(20, 54, 256, 28);
		getContentPane().add(textField);
		textField.setColumns(10);

		dlm = new DefaultListModel();
		users = new CheckBoxList();
		users.setModel(dlm);
		// ////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();

		}
		try {
			stat = connection.createStatement();
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			ResultSet idsUser = stat
					.executeQuery("SELECT idUser, name FROM User WHERE idUser <> "
							+ Test.iduser + ";");

			while (idsUser.next()) {

				CheckboxUser temp = new CheckboxUser(idsUser.getInt("idUser"),
						idsUser.getString("name"));

				// Fuegt alle Personen interner Liste zu um spaeter wieder auf
				// id
				// zurueckgreifen zu koennen.
				llUser.add(temp);

				JCheckBoxWithObject check = new JCheckBoxWithObject(temp);

				dlm.addElement(check);

			}

		} catch (SQLException e1) {
			e1.printStackTrace();
		}

		JLabel dudes = new JLabel();
		dudes.setBounds(20, 84, 256, 28);
		dudes.setText(einladen[speak]);
		getContentPane().add(dudes);

		JScrollPane bookscroller = new JScrollPane(users);
		bookscroller.setBounds(20, 114, 256, 28 * 5);
		// bookscroller.setPreferredSize(new Dimension(280, 570));
		getContentPane().add(bookscroller);

		JButton btnHinzufgen = new JButton(buttonadd[speak]);
		btnHinzufgen.setBounds(170, 266, 106, 29);
		getContentPane().add(btnHinzufgen);

		ActionListener addbtn = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				LinkedList<Integer> idadd = new LinkedList<Integer>();
				for (int i = 0; i < dlm.size(); i++) {
					JCheckBoxWithObject temp = (JCheckBoxWithObject) dlm.get(i);
					if (temp.isSelected() == true) {
						CheckboxUser temp2 = (CheckboxUser) temp.getObject();
						idadd.add(temp2.getIdUser());
					}

				}
				try {
					int idCalendar = 0;
					ResultSet entrys = stat
							.executeQuery("SELECT idCalendar FROM `sopra-ws12-awesome_fireballs`.`Calendar`ORDER BY idCalendar DESC LIMIT 1;");
					while (entrys.next()) {
						idCalendar = entrys.getInt(1) + 1;
					}

					PreparedStatement ppst = connection
							.prepareStatement("INSERT INTO Calendar VALUES( ?, ?, ?, ?, ?);");

					connection.setAutoCommit(false);

					ppst.setInt(1, idCalendar);
					ppst.setInt(2, Test.iduser);
					ppst.setString(3, textField.getText());
					ppst.setInt(4, Test.iduser);
					ppst.setInt(5, 1);
					ppst.addBatch();

					for (int i = 0; i < idadd.size(); i++) {
						ppst.setInt(1, idCalendar);
						ppst.setInt(2, idadd.get(i));
						ppst.setString(3, textField.getText());
						ppst.setInt(4, Test.iduser);
						ppst.setInt(5, 0);
						ppst.addBatch();
					}

					ppst.executeBatch();
					connection.setAutoCommit(true);
					if (openedfrom instanceof Test){
						((Test) openedfrom).updateLeftPane(true);
					}
					if (openedfrom instanceof SaveDialog){
						((SaveDialog) openedfrom).update();
					}

					dispose();

				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		};

		btnHinzufgen.addActionListener(addbtn);

		JButton btnAbbrechen = new JButton(buttoncancel[speak]);
		btnAbbrechen.setBounds(61, 266, 106, 29);
		getContentPane().add(btnAbbrechen);

		ActionListener cancle = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		};

		btnAbbrechen.addActionListener(cancle);
	}
	
	
	/**
	 * Konstruktor für neuen Kalender mit übergebener Testklasse
	 */
	public NewCalendarWindow(final SaveDialog openedfrom, final Test test) {

		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);
		speak = Integer.parseInt(or.getLanguage());

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setTitle(fenstername[speak]);

		Dimension size = new Dimension(300, 350);
		setSize(size);
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);

		setBackground(new Color(r, g, b));
		getContentPane().setLayout(null);

		JLabel name = new JLabel();
		name.setBounds(20, 24, 256, 28);
		name.setText(textname[speak]);
		getContentPane().add(name);

		textField = new JTextField();
		textField.setBounds(20, 54, 256, 28);
		getContentPane().add(textField);
		textField.setColumns(10);

		dlm = new DefaultListModel();
		users = new CheckBoxList();
		users.setModel(dlm);
		// ////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();

		}
		try {
			stat = connection.createStatement();
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			ResultSet idsUser = stat
					.executeQuery("SELECT idUser, name FROM User WHERE idUser <> "
							+ Test.iduser + ";");

			while (idsUser.next()) {

				CheckboxUser temp = new CheckboxUser(idsUser.getInt("idUser"),
						idsUser.getString("name"));

				// Fuegt alle Personen interner Liste zu um spaeter wieder auf
				// id
				// zurueckgreifen zu koennen.
				llUser.add(temp);

				JCheckBoxWithObject check = new JCheckBoxWithObject(temp);

				dlm.addElement(check);

			}

		} catch (SQLException e1) {
			e1.printStackTrace();
		}

		JLabel dudes = new JLabel();
		dudes.setBounds(20, 84, 256, 28);
		dudes.setText(einladen[speak]);
		getContentPane().add(dudes);

		JScrollPane bookscroller = new JScrollPane(users);
		bookscroller.setBounds(20, 114, 256, 28 * 5);
		// bookscroller.setPreferredSize(new Dimension(280, 570));
		getContentPane().add(bookscroller);

		JButton btnHinzufgen = new JButton(buttonadd[speak]);
		btnHinzufgen.setBounds(170, 266, 106, 29);
		getContentPane().add(btnHinzufgen);

		ActionListener addbtn = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				LinkedList<Integer> idadd = new LinkedList<Integer>();
				for (int i = 0; i < dlm.size(); i++) {
					JCheckBoxWithObject temp = (JCheckBoxWithObject) dlm.get(i);
					if (temp.isSelected() == true) {
						CheckboxUser temp2 = (CheckboxUser) temp.getObject();
						idadd.add(temp2.getIdUser());
					}

				}
				try {
					int idCalendar = 0;
					ResultSet entrys = stat
							.executeQuery("SELECT idCalendar FROM `sopra-ws12-awesome_fireballs`.`Calendar`ORDER BY idCalendar DESC LIMIT 1;");
					while (entrys.next()) {
						idCalendar = entrys.getInt(1) + 1;
					}

					PreparedStatement ppst = connection
							.prepareStatement("INSERT INTO Calendar VALUES( ?, ?, ?, ?, ?);");

					connection.setAutoCommit(false);

					ppst.setInt(1, idCalendar);
					ppst.setInt(2, Test.iduser);
					ppst.setString(3, textField.getText());
					ppst.setInt(4, Test.iduser);
					ppst.setInt(5, 1);
					ppst.addBatch();

					for (int i = 0; i < idadd.size(); i++) {
						ppst.setInt(1, idCalendar);
						ppst.setInt(2, idadd.get(i));
						ppst.setString(3, textField.getText());
						ppst.setInt(4, Test.iduser);
						ppst.setInt(5, 0);
						ppst.addBatch();
					}

					ppst.executeBatch();
					connection.setAutoCommit(true);
					test.updateLeftPane(true);
					openedfrom.update();

					dispose();

				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		};

		btnHinzufgen.addActionListener(addbtn);

		JButton btnAbbrechen = new JButton(buttoncancel[speak]);
		btnAbbrechen.setBounds(61, 266, 106, 29);
		getContentPane().add(btnAbbrechen);

		ActionListener cancle = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		};

		btnAbbrechen.addActionListener(cancle);
	}
	
	
	
}
